'use strict';
module.exports = exec;

const path = require('path')
const Package = require("@gsh-cli/package")
const { suitSpawn } = require("@gsh-cli/utils")

const SETTINGS = {
  init: '@gsh-cli/init'
}
const CACHE_DIR = 'dependencies'

async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH
  const homeDir = process.env.CLI_HOME_PATH
  let storeDir = ''
  const cmdObj = arguments[arguments.length - 1]
  const packageName = SETTINGS[cmdObj.name()]
  const packageVersion = 'lastest'
  let pkg = null
  // 如果没传targetPath参数
  if(!targetPath) {
    targetPath = path.resolve(homeDir, CACHE_DIR)
    storeDir = path.resolve(targetPath, 'node_modules')
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion
    });
    // 如果包存在
    if(await pkg.exists()) {
      // 更新
      await pkg.update()
    } else {
      // 安装
      await pkg.install()
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion
    });
  }
  const rootFile = await pkg.getRootFile()
  // 执行rootFile入口文件
  // arguments是数组，通过Array.from将伪数组转为数组
  try {
    const args = Array.from(arguments)
    const cmd = args[args.length - 1]
    let o = Object.create({})
    Object.keys(cmd).forEach(key => {
      if(cmd.hasOwnProperty(key) && !key.startsWith('_') && key !== 'parent') {
        o[key] = cmd[key]
      }
    })
    args[args.length - 1] = o
    const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`
    const child = suitSpawn('node',['-e', code], {
      cwd: process.cwd(),
      stdio: 'inherit'
    })
    // 执行出错
    child.on('error', (e) => {
      console.log(e.message)
      process.exit(1)
    })
    // 执行完毕
    child.on('exit', (e) => {
      process.exit(e)
    })
  } catch(err) {
    console.log(err)
  }
}


